package Servlet.File;

import Entity.MyTableData;
import Service.FileService.FileService;
import Service.FileService.Imp.FileServiceImp;
import Util.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.security.spec.ECField;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * Author: Deng PengFei
 * Date: 2021/9/2
 * Time: 9:53
 */

@MultipartConfig
@WebServlet(urlPatterns = {"/uploadFile", "/downloadFile", "/importInfo", "/addMsgFile"}, name = "FileServlet")
public class FileServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String url = request.getRequestURI();
        if ("/uploadFile".equals(url)) {
            uploadFile(request, response);
        } else if ("/downloadFile".equals(url)) {
            downloadFile(request, response);
        } else if ("/importInfo".equals(url)) {
            importInfo(request, response);
        } else if ("/addMsgFile".equals(url)) {
            addMsgFile(request, response);
        }
    }

    private void addMsgFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        FileService fileService = new FileServiceImp();
        String msgId = request.getParameter("id");
        String savePath = request.getParameter("savePath");
        Part part = request.getPart("file");
        String fileName = FileUtil.getFileName(part);
        String realPath = request.getServletContext().getRealPath("/file");  //文件保存的真实目录
        realPath = realPath + File.separator + savePath;
        // 判断 存放的目录是否存在 如果目录不存在则创建
        File uploadDir = new File(realPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        PrintWriter out = response.getWriter();
        part.write(realPath + File.separator + fileName);
        MyTableData myTableData = new MyTableData();
        if (fileService.updateMsgFileById(Integer.valueOf(msgId), fileName, savePath)) {
            myTableData.setMsg("上传附件成功");
        } else {
            myTableData.setMsg("上传附件失败");
        }
        String json = JSONObject.toJSONString(myTableData, SerializerFeature.WriteMapNullValue);
        out.print(json);
        out.close();
    }


    /**
     * 导入信息
     */
    private void importInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        FileService fileService = new FileServiceImp();
        //先将文件保存
        String realPath = request.getServletContext().getRealPath("/file");  //文件保存的真实目录
        String fileName = request.getParameter("fileName");  //文件名
        MyTableData myTableData = new MyTableData();
        try {
            Part part = request.getPart("file"); // 文件
            part.write(realPath + File.separator + fileName); //保存文件
            //读取文件的内容
            File file = new File(realPath + File.separator + fileName);
            ArrayList<ArrayList<String>> arrayLists = FileUtil.readExcel(file);
            String type = request.getParameter("type");
            if ("1".equals(type)) {
                myTableData = fileService.importStudent(arrayLists);
            } else if ("2".equals(type)) {
                myTableData = fileService.importTeacher(arrayLists);
            }
            myTableData.setMsg("导入成功");
            //导入后将文件删除
            file.delete();
        } catch (Exception e) {
            myTableData.setMsg("导入失败");
            e.printStackTrace();
        }
        PrintWriter out = response.getWriter();
        String json = JSONObject.toJSONString(myTableData, SerializerFeature.WriteMapNullValue);
        out.print(json);
        out.close();
    }

    /**
     * 文件下载
     */
    private void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String url = request.getParameter("url");
        String filename = request.getParameter("filename");
        //设置文件MIME类型
        response.setContentType(getServletContext().getMimeType(filename));
        //设置Content-Disposition
        response.setHeader("Content-Disposition", "attachment;filename=" + filename);
        //读取目标文件，通过response将目标文件写到客户端
        //获取目标文件的绝对路径
        String realPath = request.getServletContext().getRealPath("/file");  //文件保存的真实目录
        //System.out.println(fullFileName);
        //读取文件
        InputStream in = new FileInputStream(realPath + "/" + url + "/" + filename);
        OutputStream out = response.getOutputStream();
        //写文件
        int b;
        while ((b = in.read()) != -1) {
            out.write(b);
        }
        in.close();
        out.close();
    }

    private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        FileService fileService = new FileServiceImp();
        String realPath = request.getServletContext().getRealPath("/file");  //文件保存的真实目录
        String savePath = request.getParameter("savePath"); // 文件保存的 文件夹
        String fileName = request.getParameter("fileName");  //文件名
        String SNO = request.getParameter("SNO"); //学号
        String type = request.getParameter("type");
        String state = request.getParameter("state");
        Integer id = Integer.parseInt(request.getParameter("id"));
        Part part = request.getPart("file"); // 文件
        realPath = realPath + File.separator + savePath;
        // 判断 存放的目录是否存在 如果目录不存在则创建
        File uploadDir = new File(realPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        PrintWriter out = response.getWriter();
        MyTableData myTableData = new MyTableData();
        try {
            part.write(realPath + File.separator + fileName);
            //往数据库更新老师上传的文件路径和名字
            boolean flag = false;
            switch (state) {
                case "开题报告":
                    flag = fileService.updateReportFile(SNO, fileName, savePath, type, id);
                    break;
                case "初稿":
                    flag = fileService.updateStageCheck(SNO, fileName, savePath, "初稿");
                    break;
                case "定稿":
                    flag = fileService.updateStageCheck(SNO, fileName, savePath, "定稿");
                    break;
                case "终稿":
                    flag = fileService.updateStageCheck(SNO, fileName, savePath, "终稿");
                    break;
                default:
                    break;
            }
            if (flag) {
                myTableData.setCode(0);
                myTableData.setMsg("提交成功");
            } else {
                myTableData.setCode(1);
                myTableData.setMsg("提交失败");
            }
            String json = JSONObject.toJSONString(myTableData, SerializerFeature.WriteMapNullValue);
            out.print(json);
            out.close();
        } catch (Exception e) {
            myTableData.setCode(1);
            myTableData.setMsg("提交失败");
            String json = JSONObject.toJSONString(myTableData, SerializerFeature.WriteMapNullValue);
            out.print(json);
            out.close();
        }
    }


}
